package com.wyth.lottery.service.presenter;

import android.content.Context;
import android.content.Intent;

import com.wyth.lottery.service.Entity.Detail;
import com.wyth.lottery.service.manager.DataManager;
import com.wyth.lottery.service.view.DetailView;
import com.wyth.lottery.service.view.View;

import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by Administrator on 2017/10/19 0019.
 */

public class DetailPresenter implements Presenter{
    private DataManager manager;
    private CompositeSubscription mCompositeSubscription;
    private Context mContext;
    private DetailView mDetailView;
    private Detail mDetail;

    public DetailPresenter(Context mContext) {
        this.mContext = mContext;
    }

    @Override
    public void onCreate() {
        manager = new DataManager(mContext);
        mCompositeSubscription = new CompositeSubscription();
    }

    @Override
    public void onStart() {

    }

    @Override
    public void onStop() {
        if (mCompositeSubscription.hasSubscriptions()) {
            mCompositeSubscription.unsubscribe();
        }
    }

    @Override
    public void pause() {

    }

    @Override
    public void attachView(View view) {
        mDetailView = (DetailView) view;
    }




    @Override
    public void attachIncomingIntent(Intent intent) {

    }

    public void getDetail(String detail) {
        mCompositeSubscription.add(manager.getDetail(detail)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Detail>() {
                    @Override
                    public void onCompleted() {
                        if (mDetail != null) {
                            mDetailView.onSuccess(mDetail);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        mDetailView.onError("请求失败！！");
                    }

                    @Override
                    public void onNext(Detail detail) {
                        mDetail = detail;
                    }
                })
        );
    }



}
